package com.infonautics.action;

import java.io.File;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.common.UploadFileCommonImp;
import com.hibernate.Category;
import com.hibernate.Download;
import com.hibernate.Userinfo;
import com.infonautics.dao.ICategoryDao;
import com.infonautics.dao.IDownloadDao;
import com.infonautics.dao.imp.ICategoryDaoImp;
import com.infonautics.dao.imp.IDownloadDaoImp;
import com.infonautics.page.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.system.dao.ISystemDao;

/**
 * 体验中心控制层
 * @author Administrator
 *
 */
public class DownloadAction extends ActionSupport implements Preparable,SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Map<String,Object> session;
	private String pageUrl = "/WEB-INF/download/";
	private String successMsg;
	private String url;
	private Userinfo userinfo;
	private ISystemDao<Download> sysDao = new IDownloadDaoImp();
	private IDownloadDao downloadDao = new IDownloadDaoImp();
	private Download download;
	private ISystemDao<Category> cysDao = new ICategoryDaoImp();
	private ICategoryDao categoryDao = new ICategoryDaoImp();
	private Category category;
	private PageBean<Download> pageBean;
	private int page = 1;
	private int id;
	private String iname;
	private int type;
	private int userid;
	//文件上传
	private File upload; 
	private String uploadFileName;
    private String dir; 
    private String targetFileName;
    private String urls;
    private String uploadDir;
    private String path="";
    private String pathUrl;
    private String uploadname;
    private String upname="";
	
	/*
	 * 验证用户信息
	 * (non-Javadoc)
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		
		if(session.containsKey("userinfo") && session.get("userinfo") != null){
			
			userinfo = (Userinfo)session.get("userinfo");
		}
		
	}

	/*
	 * 查询体验中心所有信息
	 */
	public String list() throws Exception{
		
		String queryString = "";
		userid = userinfo.getId();
		if(type > 0){
			
			System.out.println(userinfo.getId());
			queryString += " and type="+type +" and userid="+userid;
		}
		pageBean = downloadDao.doQueryList(20, page, queryString);
		pageBean.setQueryString("&type="+type+"&userid="+userid);
		
		return "list";
	}
	
	/*
	 * 查询体验中心中心所有信息
	 */
	public String query() throws Exception{
		
		String queryString = "";
		userid = userinfo.getId();
		
		iname = new String(iname.getBytes("ISO8859-1"),"UTF-8");
		
		if(iname != null && !iname.equals("")){
			
			queryString +=" and name like '%"+iname+"%'";
		}
		queryString += " and type="+type+" and userid="+userid;
		
		pageBean = downloadDao.doQueryList(20, page, queryString);
		pageBean.setQueryString("&type="+type+"&userid="+userid+"&iname="+iname);
		
		return "list";
	}
	
	/*
	 * 跳转到添加下载页面
	 */
	public String addPage() throws Exception{
		return "input";
	}
	
	/*
	 * 添加下载产品信息
	 */
	public String add() throws Exception{
		
		String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		download.setPubtime(Timestamp.valueOf(now));
		
		if(upload != null){
			
			// 获得upload路径的实际目录 
	        String realPath = ServletActionContext.getServletContext().getRealPath(uploadDir); 
	        
        	//获得实际目录 
        	String targetDirectory = realPath; 
        	String mydir = ""; 
        	String tname = ""; 
        	String url = "";
        	
        	// 生成保存文件的文件名称 
        	tname = generateFileName(uploadFileName); 
        	
        	// 保存文件的路径 
        	mydir = targetDirectory + "/" + tname; 
        	
        	url = uploadDir + "/" + tname;
        	
        	upname+=uploadFileName+"|";
        	
        	setUploadname(upname);//文件中文名
        	
        	path+= url+"|";
        	
        	setPathUrl(path);//文件路径
        	
        	// 建立一个目标文件 
        	File target = new File(targetDirectory, tname); 
        	
        	// 将临时文件复制到目标文件 
        	FileUtils.copyFile(upload, target);
        	
        	setDir(mydir); 
        	setTargetFileName(tname); 
        	setUrls(url);
        	
        	String path_1 = pathUrl.substring(0,pathUrl.lastIndexOf("|"));
        	
        	download.setUppath(path_1);
		}
		
		sysDao.doAdd(download);
		System.out.println(download.getCategory().getId());
		doMsgHandle("添加成功", "Download_list.action?type="+download.getCategory().getId());
		return DownloadAction.SUCCESS;
	}
	
	/*
	 * 跳转到修改下载产品页面
	 */
	public String modifyPage() throws Exception{
		
		download = sysDao.doOne(id);
		return "input";
	}
	
	/*
	 * 修改下载产品
	 */
	public String modify() throws Exception{
		
		String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		download.setPubtime(Timestamp.valueOf(now));
		
		if(upload != null){
			
			//删除路径下图片
			String realFilePath=ServletActionContext.getServletContext().getRealPath(download.getUppath());
			UploadFileCommonImp.doUploadFileDelete(realFilePath);
			
			// 获得upload路径的实际目录 
	        String realPath = ServletActionContext.getServletContext().getRealPath(uploadDir); 
	       
        	//获得实际目录 
        	String targetDirectory = realPath; 
        	String mydir = ""; 
        	String tname = ""; 
        	String url = "";
        	
        	// 生成保存文件的文件名称 
        	tname = generateFileName(uploadFileName); 
        	
        	// 保存文件的路径 
        	mydir = targetDirectory + "/" + tname; 
        	
        	url = uploadDir + "/" + tname;
        	
        	upname+=uploadFileName+"|";
        	
        	setUploadname(upname);//文件中文名
        	
        	path+= url+"|";
        	
        	setPathUrl(path);//文件路径
        	
        	// 建立一个目标文件 
        	File target = new File(targetDirectory, tname); 
        	
        	// 将临时文件复制到目标文件 
        	FileUtils.copyFile(upload, target);
        	
        	setDir(mydir); 
        	setTargetFileName(tname); 
        	setUrls(url);
        	
        	String path_1 = pathUrl.substring(0,pathUrl.lastIndexOf("|"));
        	
        	download.setUppath(path_1);
		}else{
			
			download.setUppath(download.getUppath());
		}

		sysDao.doModfiy(download);
		doMsgHandle("修改成功", "Download_list.action?type="+download.getCategory().getId());
		return DownloadAction.SUCCESS;
	}
	
	/*
	 * 删除下载产品
	 */
	public String delete() throws Exception{
		
		download = sysDao.doOne(id);
		
		//删除路径下图片
		String realFilePath=ServletActionContext.getServletContext().getRealPath(download.getUppath());
		UploadFileCommonImp.doUploadFileDelete(realFilePath);
		
		sysDao.doDelete(id);
		
		System.out.println("---------------------"+download.getCategory().getId());
		doMsgHandle("删除成功", "Download_list.action?type="+download.getCategory().getId());
		return DownloadAction.SUCCESS;
	}
	/*
	 * 服务服务方法
	 */
	private void doMsgHandle(String successMsg,String url){
		this.successMsg=successMsg;
		this.url=url;
	}
	
	// 为上传文件自动分配文件名称，避免重复 
    private String generateFileName(String fileName) { 
    	
        // 获得当前时间 
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss"); 
        
        // 转换为字符串 
        String formatDate = format.format(new Date()); 
        
        // 随机生成文件编号 
        int random = new Random().nextInt(10000); 
        
        // 获得文件后缀名称 
        int position = fileName.lastIndexOf("."); 
        
        //从左面截取获得文件后缀名
        String extension = fileName.substring(position); 
        
        // 组成一个新的文件名称 
       return formatDate + random + extension; 
    }
	
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getTargetFileName() {
		return targetFileName;
	}

	public void setTargetFileName(String targetFileName) {
		this.targetFileName = targetFileName;
	}

	public String getUrls() {
		return urls;
	}

	public void setUrls(String urls) {
		this.urls = urls;
	}

	public String getUploadDir() {
		return uploadDir;
	}

	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getPathUrl() {
		return pathUrl;
	}

	public void setPathUrl(String pathUrl) {
		this.pathUrl = pathUrl;
	}

	public String getUploadname() {
		return uploadname;
	}

	public void setUploadname(String uploadname) {
		this.uploadname = uploadname;
	}

	public String getUpname() {
		return upname;
	}

	public void setUpname(String upname) {
		this.upname = upname;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public String getSuccessMsg() {
		return successMsg;
	}

	public void setSuccessMsg(String successMsg) {
		this.successMsg = successMsg;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getPageUrl() {
		return pageUrl;
	}

	public void setPageUrl(String pageUrl) {
		this.pageUrl = pageUrl;
	}

	public Userinfo getUserinfo() {
		return userinfo;
	}

	public void setUserinfo(Userinfo userinfo) {
		this.userinfo = userinfo;
	}

	public Download getDownload() {
		return download;
	}

	public void setDownload(Download download) {
		this.download = download;
	}

	public PageBean<Download> getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean<Download> pageBean) {
		this.pageBean = pageBean;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getIname() {
		return iname;
	}

	public void setIname(String iname) {
		this.iname = iname;
	}

	public Map<String, Object> getSession() {
		return session;
	}
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
		
	}

	
}
